package com.pocketpets.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map.Entry;
import java.util.Properties;
import android.util.Log;

public class HttpJsonConnection {

	// ================================================================
	// Methods
	// ================================================================

	static public String callService(String serviceName, int ctl,
			Properties parameters) {
		String stringBuffer = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			StringBuilder jString = new StringBuilder();
			// construct URL
			StringBuilder sb = new StringBuilder();
			sb.append(Constants.BASE_URL);
			sb.append(serviceName).append(".php?");
			sb.append("CTL=").append(ctl);
			for (Entry<Object, Object> entry : parameters.entrySet()) {
				sb.append('&')
						.append(entry.getKey())
						.append('=')
						.append(URLEncoder.encode(entry.getValue().toString(),
								"UTF-8"));
			}
			Log.i("HTTP LINK", sb.toString());

			// get HTTP response
			URL url = new URL(sb.toString());
			URLConnection conn = url.openConnection();
			isr = new InputStreamReader(conn.getInputStream());
			br = new BufferedReader(isr);
			while (true) {
				stringBuffer = br.readLine();
				if (stringBuffer != null)
					jString.append(stringBuffer);
				else
					break;
			} // while
			String tempString = jString.toString();
			String newString = null;
			if (null != tempString) {
				newString = tempString.substring(tempString.indexOf("(") + 1,
						tempString.indexOf(")"));
			}
			return newString;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				br = null;
			}
			if (null != isr) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				isr = null;
			}
		}
	}

}
